//
//  AddGoodsViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/8/25.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "AddGoodsViewController.h"

#import "SPManagerViewController.h"
@interface AddGoodsViewController ()<UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIPickerViewDelegate,UIPickerViewDataSource>
{
    UIImagePickerController *imagepc;
    UIView *bottomView;
}
@property (weak, nonatomic) IBOutlet UITextField *text1;
@property (weak, nonatomic) IBOutlet UITextView *text2;
@property (weak, nonatomic) IBOutlet UILabel *labFenlei;
@property (weak, nonatomic) IBOutlet UITextField *text3;
@property (weak, nonatomic) IBOutlet UIImageView *images;

@property (nonatomic,copy) NSString *imgUrl;//图片上传路径
@property (nonatomic,strong) NSMutableArray *array;//数据源
@property (nonatomic,copy) NSString *str;
@property (nonatomic,copy) NSString *strid;

@end

@implementation AddGoodsViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    
    [self showNav:@"添加商品"];
    _array = [NSMutableArray array];
    _text2.layer.cornerRadius = 5.0;
    _text2.layer.borderWidth = 1.0;
    _text2.layer.borderColor = COLOR_RGB(242, 242, 242, 1).CGColor;
    _text2.delegate = self;
    _text2.text = @"请填写";
    _text2.textColor = [UIColor grayColor];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickImage)];
    _images.userInteractionEnabled = YES;
    [_images addGestureRecognizer:tap];
    
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click2)];
    _labFenlei.userInteractionEnabled = YES;
    [_labFenlei addGestureRecognizer:tap2];
    
    [self loadData];
    
}

- (void)click2{
    bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight-250, ScreenWidth, 250)];
    bottomView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:bottomView];
    
    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn1.frame = CGRectMake(10, 0, 40, 40);
    [btn1 setTitle:@"取消" forState:UIControlStateNormal];
    [btn1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [btn1 addTarget:self action:@selector(clickCancel) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:btn1];
    
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn2.frame = CGRectMake(ScreenWidth-50, 0, 40, 40);
    [btn2 setTitle:@"确定" forState:UIControlStateNormal];
    [btn2 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [btn2 addTarget:self action:@selector(clickSure) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:btn2];
    
    UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 40, ScreenWidth, 210)];
    pickerView.dataSource = self;
    pickerView.delegate = self;
    [bottomView addSubview:pickerView];
    
}

- (void)clickCancel{
    [bottomView removeFromSuperview];
}

- (void)clickSure{
    if (_str.length > 0) {
        [bottomView removeFromSuperview];
        _labFenlei.text = _str;
    }
}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return _array.count;
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    NSString *str = [_array[row] objectForKey:@"name"];
    return str;
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    NSString *str = [_array[row] objectForKey:@"name"];
    _strid = [_array[row] objectForKey:@"id"];
    _str = str;
    NSLog(@"str:%@",str);
}

//拍照上传
- (void)clickImage{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPicture];
    }];
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从相册中获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPictureFromAlbum];
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    [self presentViewController:alert animated:YES completion:nil];
}

//拍照获取
- (void)pickerPicture{
    if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
        NSLog(@"用前置摄像头");
        imagepc = [[UIImagePickerController alloc] init];
        imagepc.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagepc.delegate = self;
        imagepc.allowsEditing = YES;
        imagepc.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        
    }else if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]){
        NSLog(@"用后置摄像头");
        imagepc = [[UIImagePickerController alloc] init];
        imagepc.cameraDevice = UIImagePickerControllerCameraDeviceFront;
    }else{
        UIAlertController *a = [UIAlertController alertControllerWithTitle:@"调用失败" message:@"请从手机相册中选择" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:a animated:YES completion:nil];
    }
    
    [self presentViewController:imagepc animated:YES completion:nil];
}

//从手机的图片获取
- (void)pickerPictureFromAlbum{
    UIImagePickerController *imgpicker = [[UIImagePickerController alloc] init];
    imgpicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imgpicker.allowsEditing = YES;
    imgpicker.delegate = self;
    [self presentViewController:imgpicker animated:YES completion:nil];
    
}
#pragma -mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
    _images.image = img;
    [self loadImage:img];
    [self dismissViewControllerAnimated:YES completion:nil];
}
//图片上传
- (void)loadImage:(UIImage *)image{
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:@"pic.png" forKey:@"pic"];
    [parmas setObject:@"name" forKey:@"name"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = [NSString stringWithFormat:@"%@/App/Norm/upload",urlHead];
    [manager POST:url parameters:parmas constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        [formData appendPartWithFileData:data name:@"pic" fileName:fileName mimeType:@"image/png"];
        [formData appendPartWithFileData:data name:@"name" fileName:fileName mimeType:@"image/png"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *op = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
        NSLog(@"dic:%@",op);
        NSString *error = [NSString stringWithFormat:@"%li",[[op objectForKey:@"error"] integerValue]];
        if ([error integerValue] == 200) {
            _imgUrl = [op objectForKey:@"result"];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
    }];

}

#pragma mark - UITextViewDelegate
-(void)textViewDidBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@"请填写"]) {
        textView.text = @"";
        textView.textColor = [UIColor blackColor];
    }
}

-(void)textViewDidEndEditing:(UITextView *)textView{
    if (textView.text.length < 1) {
        textView.text = @"请填写";
        textView.textColor = [UIColor grayColor];
    }
}
//添加
- (IBAction)click:(id)sender {
    if (_text1.text.length == 0) {
        [self showAlert:@"请输入商品"];
        return;
    }else if (_text2.text.length > 30 || [_text2.text isEqualToString:@""]){
        [self showAlert:@"商品简介不得超过30个字"];
    }else if (_text3.text.length == 0){
        [self showAlert:@"请输入价格"];
        return;
    }else if (_str.length == 0){
        [self showAlert:@"请选择商品类型"];
        return;
    }else if (_imgUrl.length == 0){
        [self showAlert:@"请选择图片"];
        return;
    }
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:_merid forKey:@"merchantid"];
    [parmas setObject:_strid forKey:@"classid"];
    [parmas setObject:_text1.text forKey:@"name"];
    [parmas setObject:_imgUrl forKey:@"img"];
    [parmas setObject:_text3.text forKey:@"price"];
    [parmas setObject:_text2.text forKey:@"introduction"];
    NSLog(@"parmas:%@",parmas);
    NSString *url = [NSString stringWithFormat:@"%@/App/Cleaning/upload",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"res:%@",responseObject);
        NSString *error = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"error"] integerValue]];
        if ([error integerValue] == 200) {
            [self.navigationController popViewControllerAnimated:YES];
        }
        [SVProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD dismiss];
    }];
    
}
//干洗-类别
- (void)loadData{
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:_merid forKey:@"merchantid"];
    NSString *url = [NSString stringWithFormat:@"%@/App/Cleaning/classtype",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"res:%@",responseObject);
        NSString *error = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"error"] integerValue]];
        if ([error integerValue] == 200) {
            _array = [responseObject objectForKey:@"result"];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
